package com.gkzf.ai.module.crm.util.packaging;

import com.alibaba.fastjson.JSONObject;
import com.gkzf.ai.module.crm.controller.admin.creditReport.vo.creditreportdetails.CreditReportDetailsSaveReqVO;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Predicate;

import static com.gkzf.ai.module.crm.util.AnalysisJsonObjectUtils.*;

/**
 *  计算账户信息汇总
 *  非循环贷
 *  循环贷一
 *  循环贷二
 *  贷记卡
 */
public class CalculationAccountSummary {

    public void extractAccountSummary (Map<String, Object> basic, CreditReportDetailsSaveReqVO detailsDO) {
        for (Map.Entry<String, Object> basicMap : basic.entrySet()) {
            String nextKey = basicMap.getKey();
            Object value = basicMap.getValue();
            JSONObject jsonObjectValue = convertJSONObject(value);
            switch (nextKey) {
                case "非循环贷账户信息汇总":
                    //非循环贷账户信息汇总
                    getDebtCyclical(1, jsonObjectValue,detailsDO);
                    break;
                case "循环贷账户二信息汇总":
                    //循环贷账户二信息汇总
                    getDebtCyclical(3,jsonObjectValue,detailsDO);
                    break;
                case "循环贷账户一信息汇总":
                    //循环贷账户一信息汇总
                    getDebtCyclical(2,jsonObjectValue,detailsDO);
                    break;
                case "贷记卡账户信息汇总":
                    //贷记卡账户信息汇总
                    getDebtCyclical(4,jsonObjectValue,detailsDO);
                    break;
                case "准贷记卡账户信息汇总":
                    //贷记卡账户信息汇总
                    getDebtCyclical(5,jsonObjectValue,detailsDO);
                    break;
                default:
                    break;

            }
        }
    }

    public JSONObject convertJSONObject(Object value){
        if (Objects.nonNull(value) && value instanceof List){
            List valueMap = (List)value;
            if(!valueMap.isEmpty()){
               return JSONObject.parseObject(JSONObject.toJSONString(valueMap.get(0)));

            }
        }
        return new JSONObject();
    }

    /**
     *  获取负债概要
     * @param type
     * @param objects
     * @return
     */
    public static void getDebtCyclical(Integer type,JSONObject objects , CreditReportDetailsSaveReqVO reportDetailsSaveReqVO){
        if (Objects.isNull(objects)){
            return;
        }
        String accountNumber = convertMoney((String)objects.get(ACCOUNT_NUMBER));
        String totalAmount = convertMoney((String)objects.get(CREDIT_LINE));
        String balance = convertMoney((String)objects.get(BALANCE));
        String averageServiceRate = convertMoney((String)objects.get(AVERAGE_SERVICE_REPAYMENT));
        if (type == 1){
            totalAmount = convertMoney((String)objects.get(TOTAL_CREDIT_LINE));
            reportDetailsSaveReqVO.setDebtNonCyclicalAccountCount(Integer.valueOf(accountNumber));
            reportDetailsSaveReqVO.setDebtNonCyclicalGrossAmount(new BigDecimal(totalAmount));
            reportDetailsSaveReqVO.setDebtNonCyclicalBalance(new BigDecimal(balance));
            reportDetailsSaveReqVO.setDebtNonCyclicalMonthAverage(new BigDecimal(averageServiceRate));
        }else if (type == 2){
            reportDetailsSaveReqVO.setDebtOneCyclicalAccountCount(Integer.valueOf(accountNumber));
            reportDetailsSaveReqVO.setDebtOneCyclicalGrossAmount(new BigDecimal(totalAmount));
            reportDetailsSaveReqVO.setDebtOneCyclicalBalance(new BigDecimal(balance));
            reportDetailsSaveReqVO.setDebtOneCyclicalMonthAverage(new BigDecimal(averageServiceRate));
        }
        else if (type == 3){
            reportDetailsSaveReqVO.setDebtTowCyclicalAccountCount(Integer.valueOf(accountNumber));
            reportDetailsSaveReqVO.setDebtTowCyclicalGrossAmount(new BigDecimal(totalAmount));
            reportDetailsSaveReqVO.setDebtTowCyclicalBalance(new BigDecimal(balance));
            reportDetailsSaveReqVO.setDebtTowCyclicalMonthAverage(new BigDecimal(averageServiceRate));
        }else if (type == 4 || type == 5){
            // 贷记卡和准贷记卡汇总
            // 获取数据中的
            String cardAccountNumber = convertMoney((String)objects.get(ACCOUNT_NUMBER));
            String cardIssuerNumber = convertMoney((String)objects.get(HAIRPIN_INSTITUTION_NUMBER));
            String cardAcountNumber = convertMoney((String)objects.get(AVERAGE_SERVICE_RATE));
            String cardTotalAmount = convertMoney((String)objects.get(TOTAL_CREDIT_LINE));
            String cardBalance = convertMoney((String)objects.get(USED_CREDIT));
            // 获取对象中的  如果对象中的数值为 null 则 默认 0
            reportDetailsSaveReqVO.setCreditCardOrgNumber(Optional.ofNullable(reportDetailsSaveReqVO.getCreditCardOrgNumber()).orElse(0)+Integer.parseInt(cardIssuerNumber));
            reportDetailsSaveReqVO.setCreditCardAccountNumber(Optional.ofNullable(reportDetailsSaveReqVO.getCreditCardAccountNumber()).orElse(0)+Integer.parseInt(cardAccountNumber));
            reportDetailsSaveReqVO.setCreditCardMaxMoney(Optional.ofNullable(reportDetailsSaveReqVO.getCreditCardMaxMoney()).orElse(BigDecimal.ZERO).add(new BigDecimal(cardTotalAmount)));
            reportDetailsSaveReqVO.setCreditCardUsedCredit(Optional.ofNullable(reportDetailsSaveReqVO.getCreditCardUsedCredit()).orElse(BigDecimal.ZERO).add(new BigDecimal(cardBalance)));
            reportDetailsSaveReqVO.setCreditCardMonthAverage(Optional.ofNullable(reportDetailsSaveReqVO.getCreditCardMonthAverage()).orElse(BigDecimal.ZERO).add(new BigDecimal(cardAcountNumber)));
            reportDetailsSaveReqVO.setCreditCardCurrentRate(ratio().apply(new BigDecimal(cardBalance), new BigDecimal(cardTotalAmount)));
            reportDetailsSaveReqVO.setCreditCardMonthRete(ratio().apply(new BigDecimal(cardAcountNumber), new BigDecimal(cardTotalAmount)));

        }
    }


    public static Boolean convert(String money){
        Predicate.isEqual("null").negate().test(money);
       Predicate<String> notNull =  string -> money != null;
        Predicate<String> aNull = notNull.and(string -> !money.equals("null"));
        return aNull.test(money);
    }


    public static BiFunction<BigDecimal, BigDecimal, BigDecimal> ratio() {
        // 1. 定义一个 BiFunction 来计算百分比率
        return  (numerator, denominator) -> {
                    if (numerator.compareTo(BigDecimal.ZERO) > 0 && denominator.compareTo(BigDecimal.ZERO) > 0) {
                        return numerator.divide(denominator, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
                    } else {
                        return BigDecimal.ZERO;
                    }
                };
    }
}


